import 'package:aero_frisbee/app/model/login_respose_model/login_respose_model.dart';
import 'package:aero_frisbee/app/req/af_req_api.dart';
import 'package:aero_frisbee/core/state/view_state.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

part 'af_login_view_model.g.dart';

@riverpod
class AfLoginAppleService extends _$AfLoginAppleService {
  @override
  ViewState<LoginResposeModel> build() {
    return const ViewState.idle();
  }

  appleLogin() async {
    state = const ViewState.loading();
    try {
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      final api = ref.watch(appApiProvider);
      final user = await api.oauthLogin(
        token: credential.identityToken ?? '',
        oauthType: 3,
      );
      state = ViewState.ready(user);
    } on SignInWithAppleAuthorizationException catch (_) {
      state = const ViewState.idle();
    } catch (e) {
      state = ViewState.error(error: e.toString());
    }
  }

  fastLogin() async {
    state = const ViewState.loading();
    try {
      final deviceId = await FlutterUdid.udid;
      final api = ref.watch(appApiProvider);
      final user = await api.oauthLogin(
        token: deviceId,
        oauthType: 4,
      );
      state = ViewState.ready(user);
    } catch (e) {
      state = ViewState.error(error: e.toString());
    }
  }
}
